/*
 * AbstractDao.java
 *
 * Created on August 12, 2007, 12:46 PM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package tcc.dao;

import java.io.Serializable;
import java.util.List;
import tcc.exception.business.ComponenteCadatradoException;
import tcc.util.PersistenceUtil;
import javax.persistence.Query;

/**
 *
 * @author Diego
 */
public abstract class AbstractDao {
    
    /** Creates a new instance of AbstractDao */
    protected AbstractDao() {
    }
    
    protected<T> List<T> find(Class<T> clazz, Criteria c){
        StringBuilder sb = new StringBuilder("from "+clazz+" \n");
        if (c!= null){
            sb.append(c.listCriteria());
        }
        Query query = PersistenceUtil.getInstance().getEntityManager().createQuery(sb.toString());
        return query.getResultList();
    }

    protected<T> T findUnique(Class<T> clazz, Criteria c){
        StringBuilder sb = new StringBuilder("from "+clazz+" \n");
        if (c!= null){
            sb.append(c.listCriteria());
        }
        Query query = PersistenceUtil.getInstance().getEntityManager().createQuery(sb.toString());
        return clazz.cast(query.getSingleResult());
    }
    
    protected void  save(Object o) {
        PersistenceUtil.getInstance().getEntityManager().merge(o);
    }
    
    protected void  delete(Object o) {
        PersistenceUtil.getInstance().getEntityManager().remove(o);
    }
    
    protected <T> T findById(Class<T> clazz, Serializable id){
        return  PersistenceUtil.getInstance().getEntityManager().find(clazz,id);
    }
    
}
